package com.benshou.bsoa.common.quartz;

import jakarta.annotation.Resource;
import org.quartz.JobKey;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

@Component
public class QuartzJobScanner {

    @Resource
    private ApplicationContext applicationContext;

    /**
     * 获取所有带有 @QuartzJob 注解的 JobKey
     *
     * @return 所有 JobKey 的集合
     */
    public Set<JobKey> getDefinedJobKeys() {
        Set<JobKey> jobKeys = new HashSet<>();

        // 获取所有 Bean 的名称
        String[] beanNames = applicationContext.getBeanDefinitionNames();

        // 遍历所有 Bean
        for (String beanName : beanNames) {
            Object bean = applicationContext.getBean(beanName);

            // 获取目标类（处理代理对象）
            Class<?> targetClass = AopUtils.getTargetClass(bean);

            // 扫描类中的方法
            for (Method method : targetClass.getDeclaredMethods()) {
                if (method.isAnnotationPresent(QuartzJob.class)) {
                    JobKey jobKey = new JobKey(method.getName(), bean.getClass().getName());
                    jobKeys.add(jobKey);
                }
            }
        }

        return jobKeys;
    }
}